﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZK.HardWareHelper
{
   

    /// <summary>
    /// 串口通讯
    /// </summary>
    public class SerialCommunication
    {
        public static int dataNum = 0;//返回的第三位数据
        public SerialPort serialPort = null;//实例
        public int res = -1;//打开和关闭的状态

        public SerialCommunication(string portName)
        {
            serialPort = new SerialPort(portName);
        }
        public SerialCommunication(string portName, int baudRate)
        {
            serialPort = new SerialPort(portName, baudRate);
        }
        public SerialCommunication(string portName, int baudRate, Parity parity)
        {
            serialPort = new SerialPort(portName, baudRate, parity);
        }
        public SerialCommunication(string portName, int baudRate, Parity parity, int dataBits)
        {
            serialPort = new SerialPort(portName, baudRate, parity, dataBits);
        }
        public SerialCommunication(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        }
        /// <summary>
        /// 打开串口通讯
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            bool boolRes = true;
            try
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                }
                serialPort.DataReceived += SerialPort_DataReceived;
            }
            catch (Exception ex)
            {
                boolRes = false;
            }
            return boolRes;
        }
        /// <summary>
        /// 读取数据委托
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //byte[] buffer = new byte[serialPort.BytesToRead];
            byte[] buffer = new byte[8];
            serialPort.Read(buffer, 0, buffer.Length);
            if (buffer.Length >= 4)
            {
                res = buffer[2];

            }
        }
        /// <summary>
        /// 关闭串口连接
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            bool res = true;
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                res = false;
            }
            return res;
        }
    }
}
